package com.rtx.express.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.dewu.sdk.base.BaseClient;
import com.dewu.sdk.base.OpenResult;
import com.dewu.sdk.factory.Factory;
import com.dewu.sdk.oauth.req.GetTokenReq;
import com.dewu.sdk.oauth.req.RefreshTokenReq;
import com.dewu.sdk.oauth.res.AuthTokenRes;
import com.dewu.sdk.order.req.BrandStraightExpressSheetRequest;
import com.dewu.sdk.order.req.BrandStraightOrderLogisticNoRequest;
import com.dewu.sdk.order.res.ExpressSheetResponse;
import com.dewu.sdk.order.res.OrderLogisticNoResponse;
import com.rtx.api.annotation.RtxExpressApi;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.express.service.IExpressService;

import cn.hutool.core.lang.UUID;

@RtxExpressApi(expressApiName = "得物直发")
@SuppressWarnings("all")
@Service("快递接口DW")
public class DWExpressAPI  implements IExpressService{
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	
	private static String appKey ="09d821ecd8fc403685083abe2c6a69c0";
	private static String appSecret ="0e05716a23674e43a3686686c8b29e5b92babab9cb6f4123a6a3cc3af97c7647";
	private static String refresh_token ="wTocGkdnRaRddqoG6kzNrJxcVYqBeP5ZU1kz52yrbpHigTfIAs9mptzCf9DUvYYI";
	//迪克斯
	//{"code":200,"data":{"access_token":"byZoz8HRvmmz4R8S8YcZXlsUiFMVFTV0DGso2jO0kirs94lNF1Nw2z8RHJnmZQQe","access_token_expires_in":"86400","open_id":"HlGLAoYL5I1ktRHN","refresh_token":"wTocGkdnRaRddqoG6kzNrJxcVYqBeP5ZU1kz52yrbpHigTfIAs9mptzCf9DUvYYI","refresh_token_expires_in":"15552000","scope":["all"]},"msg":"success"}

	//暇步士
	//{"code":200,"data":{"access_token":"tFuRlyafRl1ZDLYGBvt71Am1CGMgq5k7ugLnDM2wn8iaQhtDdCbGk6sa6O6WVRZw","access_token_expires_in":"86400","open_id":"teY2N9rXvgJe0JNy","refresh_token":"ZeMSMNjXB02deI7owoln5dUnd2jPRsk8uuk7f6Sj6a52KRzbOpHzmceA8bsltipz","refresh_token_expires_in":"15552000","scope":["all"]},"msg":"success"}

	@Override
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApi task =  bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		try {
			String uid = UUID.randomUUID().toString();
			
			mappingConfig(config);
			
			BaseClient.Config dwconfig = new BaseClient.Config();
			dwconfig.setGatewayHost("https://openapi.dewu.com");
			dwconfig.setAppKey(appKey);
			dwconfig.setSecret(appSecret);
			dwconfig.setAuthHost("https://open.dewu.com");
			Factory.setOptions(dwconfig);
			
			RefreshTokenReq	refreshTokenRequest = new RefreshTokenReq();
			refreshTokenRequest.setRefresh_token(config.getRefreshtoken());
			OpenResult<AuthTokenRes> res = Factory.Oauth.client().refreshToken(refreshTokenRequest);
			String accesstoken = res.getData().getAccess_token();
			
			//请求获取单号
			BrandStraightOrderLogisticNoRequest logisticNoRequest = new BrandStraightOrderLogisticNoRequest();
			logisticNoRequest.setAccessToken(accesstoken);
			logisticNoRequest.setOrder_no(task.getTid());
			logisticNoRequest.setType(2);
			log.info("uid-{}-得物获取快递单号请求-{}",uid,JSON.toJSONString(logisticNoRequest));
			OpenResult<OrderLogisticNoResponse> OrderLogisticNoResponse =  Factory.Order.brandDeliverClient().getLogisticNo(logisticNoRequest);
			log.info("uid-{}-得物获取快递单号响应-{}",uid,JSON.toJSONString(OrderLogisticNoResponse));
			
			//获取打印模板
			BrandStraightExpressSheetRequest request = new BrandStraightExpressSheetRequest();
			request.setAccessToken(accesstoken);
			request.setOrder_no(task.getTid());
			request.setPrint_type(1);
//			request.setVersion(2);
			
			log.info("uid-{}-得物获取打印url请求-{}",uid,JSON.toJSONString(request));
			OpenResult<List<ExpressSheetResponse>> expressSheetResponse = Factory.Order.brandDeliverClient().getExpressSheet_v2(request);
			log.info("uid-{}-得物获取打印url响应-{}",uid,JSON.toJSONString(expressSheetResponse));
			if(200==expressSheetResponse.getCode()) {
				String pdfurl = expressSheetResponse.getData().get(0).getPdf_url();
				
				bo.setCallCreateOrderAPIData(JSON.toJSONString(expressSheetResponse));
				bo.setCallCreateOrderAPIResult("ok");
				PlExpressResult result = bo.getExpressResultFillSendAndReceiver();
				
				result.setPrintData(pdfurl);
				result.setWaybillNo(OrderLogisticNoResponse.getData().getLogistics_no());
			}
		} catch (Exception e) {
			log.error("",e);
			bo.setMsg("订单-"+task.getExternorderkey()+"-获取得物打印数据失败：" + e.getMessage());
		}
	}
	
	public void mappingConfig(PlExpressApiConfig config) {
		if(!StringUtils.hasLength(config.getRefreshtoken())) {
			config.setRefreshtoken(refresh_token);
		}
	}
	
	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {
		// TODO Auto-generated method stub
		
	}
	
	
	public static void main(String[] args) {
		BaseClient.Config dwconfig = new BaseClient.Config();
		dwconfig.setGatewayHost("https://openapi.dewu.com");
		dwconfig.setAppKey(appKey);
		dwconfig.setSecret(appSecret);
		dwconfig.setAuthHost("https://open.dewu.com");
		Factory.setOptions(dwconfig);
		
		GetTokenReq request = new GetTokenReq();
		request.setClient_id("09d821ecd8fc403685083abe2c6a69c0");
		request.setClient_secret("0e05716a23674e43a3686686c8b29e5b92babab9cb6f4123a6a3cc3af97c7647");
		request.setAuthorization_code("C5AKFUIYKOPO");
		OpenResult<AuthTokenRes> res= Factory.Oauth.client().getToken(request);
		System.out.println(JSON.toJSONString(res));
	}

}
